import type { RequestOptions, ResponseData } from '../types';
import config from '@/utils/request/config';
import { useUserStore } from '@/stores';

const { token } = useUserStore();

const fetchAdapter = async <T>(url: string, options: RequestOptions): Promise<ResponseData<T>> => {
  // 添加CSRF保护
  const headers = {
    ...config.DEFAULT_HEADERS,
    ...(token ? { 'X-XSRF-TOKEN': token } : {}),
    ...options.headers,
  };

  // 处理请求参数
  let fullUrl = url;
  if (options.params) {
    const params = new URLSearchParams();
    for (const [key, value] of Object.entries(options.params)) {
      if (value !== undefined && value !== null) {
        params.append(key, String(value));
      }
    }
    fullUrl += `?${params.toString()}`;
  }

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), options.timeout || config.TIMEOUT);

  try {
    const response = await fetch(fullUrl, {
      method: options.method || 'GET',
      headers,
      body: options.data ? JSON.stringify(options.data) : undefined,
      signal: controller.signal,
      credentials: 'include', // 确保携带cookie
    });

    clearTimeout(timeoutId);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const contentType = response.headers.get('content-type');
    let data: any;

    if (contentType && contentType.includes('application/json')) {
      data = await response.json();
    } else {
      data = await response.text();
    }

    const headersObj: Record<string, string> = {};
    response.headers.forEach((value, key) => {
      headersObj[key] = value;
    });

    return {
      status: response.status,
      statusText: response.statusText,
      headers: headersObj,
      data: data as T,
    };
  } catch (error) {
    clearTimeout(timeoutId);
    if (error instanceof Error && error.name === 'AbortError') {
      throw new Error('Request timeout');
    }
    throw error;
  }
};

export default fetchAdapter;
